//
//  ServiceEvaluationViewController.m
//  LocomotiveGuards
//
//  Created by apple on 15/11/30.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "ServiceEvaluationViewController.h"
#import "UITextView+Placeholder.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
#import "SearchAreas.h"

#define BACKGROUND_COLOR_GRAY [UIColor colorWithRed:247.f/255.f green:248.f/255.f blue:248.f/255.f alpha:1.0f]
#define SEPARATOR_LINE_COLOR_GRAY [UIColor colorWithRed:230.f/255.f green:230.f/255.f blue:230.f/255.f alpha:1.0f]
#define TEXT_COLOR_GRAY [UIColor grayColor]
#define TEXT_COLOR_BLUE [UIColor colorWithRed:(CGFloat)45/255 green:(CGFloat)143/255 blue:(CGFloat)247/255 alpha:1.0]

@interface ServiceEvaluationViewController () <UIPickerViewDataSource,UIPickerViewDelegate,UITextViewDelegate>
{
    NSDictionary *_userListDic;
    NSDictionary *_newestDict;
    NSArray *_commentsArray;
    UIView *_maskView;
    UIView *_alertView;
    SearchAreas *_searchArea;
    NSArray *_distArray;
    NSArray *_lpsArray;
    UIPickerView *_distPicker;
    UIPickerView *_lpsPicker;
    BOOL start;
    BOOL end;
}

@property (nonatomic,strong) UIView *newestBgView;
@property (nonatomic,strong) UILabel *newestTimeLabel;
@property (nonatomic,strong) UILabel *newestContentLabel;
@property (nonatomic,strong) UILabel *newestLine;
@property (nonatomic,strong) UILabel *myEvalueLabel;
@property (nonatomic,strong) UIView *evalueBgView;
@property (nonatomic,strong) UILabel *noEvalueLabel;
@property (nonatomic,strong) UILabel *evalueTipLabel;
@property (nonatomic,strong) UITextView *evalueContentField;
@property (nonatomic,strong) UILabel *evalueLine;
@property (nonatomic,strong) UILabel *policeLabel;
@property (nonatomic,strong) UIButton *districtBtn;
@property (nonatomic,strong) UIButton *policeBtn;
@property (nonatomic,strong) UIImageView *inputBgView;
@property (nonatomic,strong) UITextView *inputField;
@property (nonatomic,strong) UIButton *upvoteBtn;
@end

@implementation ServiceEvaluationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.rightbtn removeFromSuperview];
    [self.centerbtn setImage:nil forState:UIControlStateNormal];
    [self.centerbtn setTitle:@"服务评价" forState:UIControlStateNormal];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.leftbtn addTarget:self action:@selector(goBackButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    _searchArea = [[SearchAreas alloc] init];
    [self configView];
    [self getUserInfoRequest];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)configView
{
    //最新点赞消息背景
    _newestBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 20+44*H, SCREEN_WIDTH, 35*H)];
    _newestBgView.backgroundColor = BACKGROUND_COLOR_GRAY;
    
    //最新点赞消息时间
    _newestTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(30*W, 3*H, 40*W, 29*H)];
    _newestTimeLabel.textColor = TEXT_COLOR_GRAY;
    _newestTimeLabel.font = [UIFont systemFontOfSize:13];
    [_newestBgView addSubview:_newestTimeLabel];
    
    //最新点赞消息内容
    _newestContentLabel = [[UILabel alloc] initWithFrame:CGRectMake(75*W, 3*H, 240*W, 29*H)];
    _newestContentLabel.textColor = TEXT_COLOR_GRAY;
    _newestContentLabel.font = [UIFont systemFontOfSize:13];
    [_newestBgView addSubview:_newestContentLabel];
    
    //分割线
    _newestLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 35*H-1, SCREEN_WIDTH, 1)];
    _newestLine.backgroundColor = SEPARATOR_LINE_COLOR_GRAY;
    [_newestBgView addSubview:_newestLine];
    [self.view addSubview:_newestBgView];
    
    //我的评价
    _myEvalueLabel = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-60*W)/2, CGRectGetMaxY(_newestBgView.frame)+10*H, 60*W, 25*H)];
    _myEvalueLabel.text = @"我的评价";
    _myEvalueLabel.textColor = TEXT_COLOR_BLUE;
    _myEvalueLabel.textAlignment = NSTextAlignmentCenter;
    _myEvalueLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:_myEvalueLabel];
    
    //评价内容背景
    _evalueBgView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_myEvalueLabel.frame), SCREEN_WIDTH, 80*H)];
    _evalueBgView.backgroundColor = BACKGROUND_COLOR_GRAY;
    
    //当前没有评价
    _noEvalueLabel = [[UILabel alloc] initWithFrame:CGRectMake(30*W, 25*H, SCREEN_WIDTH-60*W, 20*H)];
    _noEvalueLabel.text = @"您目前没有评价";
    _noEvalueLabel.textAlignment = NSTextAlignmentCenter;
    _noEvalueLabel.textColor = TEXT_COLOR_GRAY;
    _noEvalueLabel.font = [UIFont systemFontOfSize:13];
    [_evalueBgView addSubview:_noEvalueLabel];
    
    //评价提示
    _evalueTipLabel = [[UILabel alloc] initWithFrame:CGRectMake(30*W, 5*H, SCREEN_WIDTH-40*W, 20*H)];
    _evalueTipLabel.textColor = TEXT_COLOR_GRAY;
    _evalueTipLabel.font = [UIFont systemFontOfSize:13];
    [_evalueBgView addSubview:_evalueTipLabel];

    //评价内容
    _evalueContentField = [[UITextView alloc] initWithFrame:CGRectMake(30*W, 25*H, SCREEN_WIDTH-60*W, 50*H)];
    _evalueContentField.backgroundColor = [UIColor clearColor];
    _evalueContentField.textColor = TEXT_COLOR_GRAY;
    _evalueContentField.font = [UIFont systemFontOfSize:13];
    _evalueContentField.contentInset = UIEdgeInsetsMake(-8.f, -5.f, 0.f, 0.f);
    _evalueContentField.delegate = self;
    [_evalueBgView addSubview:_evalueContentField];
    
    //分割线
    _evalueLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 80*H-1, SCREEN_WIDTH, 1)];
    _evalueLine.backgroundColor = SEPARATOR_LINE_COLOR_GRAY;
    [_evalueBgView addSubview:_evalueLine];
    [self.view addSubview:_evalueBgView];
    
    //选择区按钮
    _districtBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _districtBtn.frame = CGRectMake(50*W, CGRectGetMaxY(_evalueBgView.frame)+20*H, 70*W, 30*H);
    [_districtBtn setBackgroundImage:[UIImage imageNamed:@"11pic_input01"] forState:UIControlStateNormal];
    [_districtBtn setBackgroundImage:[UIImage imageNamed:@"11pic_input01"] forState:UIControlStateHighlighted];
    _districtBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_districtBtn setTitle:@"请选择区" forState:UIControlStateNormal];
    _districtBtn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [_districtBtn setTitleColor:TEXT_COLOR_GRAY forState:UIControlStateNormal];
    [_districtBtn addTarget:self action:@selector(selectDistrict) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_districtBtn];
    
    //选择派出所按钮
    _policeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _policeBtn.frame = CGRectMake(130*W, CGRectGetMaxY(_evalueBgView.frame)+20*H, 70*W, 30*H);
    [_policeBtn setBackgroundImage:[UIImage imageNamed:@"11pic_input01"] forState:UIControlStateNormal];
    [_policeBtn setBackgroundImage:[UIImage imageNamed:@"11pic_input01"] forState:UIControlStateHighlighted];
    _policeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_policeBtn setTitle:@"请选择" forState:UIControlStateNormal];
    _policeBtn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [_policeBtn setTitleColor:TEXT_COLOR_GRAY forState:UIControlStateNormal];
    [_policeBtn addTarget:self action:@selector(selectPolicestation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_policeBtn];
    
    //派出所
    _policeLabel = [[UILabel alloc] initWithFrame:CGRectMake(200*W, CGRectGetMaxY(_evalueBgView.frame)+25*H, 50*W, 20*H)];
    _policeLabel.text = @"派出所";
    _policeLabel.textAlignment = NSTextAlignmentCenter;
    _policeLabel.textColor = TEXT_COLOR_GRAY;
    _policeLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:_policeLabel];
    
    //评价输入框背景
    _inputBgView = [[UIImageView alloc] initWithFrame:CGRectMake(20*W, CGRectGetMaxY(_districtBtn.frame)+20*H, SCREEN_WIDTH-40*W, 67*H)];
    [_inputBgView setImage:[UIImage imageNamed:@"3pic_input05"]];
    _inputBgView.userInteractionEnabled = YES;
    
    //评价输入框
    _inputField = [[UITextView alloc] initWithFrame:CGRectMake(5*W, 5*H, CGRectGetWidth(_inputBgView.frame)-10*W, CGRectGetHeight(_inputBgView.frame)-10*H)];
    _inputField.textColor = TEXT_COLOR_GRAY;
    _inputField.font = [UIFont systemFontOfSize:14];
    _inputField.placeholder = @"请输入评价";
    _inputField.backgroundColor = [UIColor clearColor];
    _inputField.delegate = self;
    [_inputBgView addSubview:_inputField];
    [self.view addSubview:_inputBgView];
    
    //点赞按钮
    _upvoteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _upvoteBtn.frame = CGRectMake((SCREEN_WIDTH-90*W)/2, CGRectGetMaxY(_inputBgView.frame)+20*H, 90*W, 30*H);
    [_upvoteBtn setBackgroundImage:[UIImage imageNamed:@"11pic_btn01"] forState:UIControlStateNormal];
    [_upvoteBtn setBackgroundImage:[UIImage imageNamed:@"11pic_btn01_on"] forState:UIControlStateHighlighted];
    [_upvoteBtn addTarget:self action:@selector(upvote) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_upvoteBtn];
}

- (void)reloadView
{
    NSNumber *timeStr = [_newestDict objectForKey:@"time"];
    long long T = [timeStr longLongValue];
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:T/1000];
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    formatter.dateFormat=@"HH:mm";
    NSString *string = [formatter stringFromDate:date];
    _newestTimeLabel.text = string;
    
    NSString *tailNum = [[_newestDict objectForKey:@"phoneNumber"] substringFromIndex:7];
    NSString *districtName = [_newestDict objectForKey:@"psbDistrict"];
    NSString *psbName = [_newestDict objectForKey:@"psbName"];
    _newestContentLabel.text = [NSString stringWithFormat:@"尾号%@用户赞了%@%@",tailNum,districtName,psbName];
    
    if (_commentsArray.count>0) {
        _noEvalueLabel.hidden = YES;
        _evalueTipLabel.hidden = NO;
        _evalueContentField.hidden = NO;
        long long latestTime = 0;
        //遍历获取最新一条评价
        for (NSInteger i=0; i<_commentsArray.count; i++) {
            long long temp = [[_commentsArray[i] objectForKey:@"time"] longLongValue];
            if (latestTime >= temp) {
                latestTime = latestTime;
            }
            else {
                latestTime = temp;
            }
        }
        //获取日期并转换成yyyy.MM.dd格式
        NSDate * latestDate = [NSDate dateWithTimeIntervalSince1970:latestTime/1000];
        formatter.dateFormat=@"yyyy.MM.dd";
        NSString *dateStr = [formatter stringFromDate:latestDate];
        
        //转换时间成HH:mm格式
        formatter.dateFormat=@"HH:mm";
        NSString *timeStr = [formatter stringFromDate:date];
        
        NSString *distStr = nil;
        NSString *psbStr = nil;
        NSString *commentStr;
        for (NSInteger i=0; i<_commentsArray.count; i++) {
            if ([[_commentsArray[i] objectForKey:@"time"] longLongValue] == latestTime) {
                distStr = [_commentsArray[i] objectForKey:@"psbDistrict"];
                psbStr = [_commentsArray[i] objectForKey:@"psbName"];
                commentStr = [_commentsArray[i] objectForKey:@"comment"];
                //当comment为空时，后台返回数据是NSNull类型，须转换成nil，不然程序会崩溃
                if ([commentStr isKindOfClass:[NSNull class]]) {
                    commentStr = nil;
                }
            }
        }
        _evalueTipLabel.text = [NSString stringWithFormat:@"%@  %@您赞了%@%@",dateStr,timeStr,distStr,psbStr];
        _evalueContentField.text = commentStr;
    }
    else {
        _evalueTipLabel.hidden = YES;
        _evalueContentField.hidden = YES;
        _noEvalueLabel.hidden = NO;
    }
}

- (UIPickerView *)showAlertWithIndex:(NSInteger)index
{
    _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _maskView.backgroundColor = [UIColor colorWithRed:100.f/255.f green:100.f/255.f blue:100.f/255.f alpha:0.5f];
    
    _alertView = [[UIView alloc] initWithFrame:CGRectMake(50*W, 170*H, SCREEN_WIDTH-100*W, 300*H)];
    _alertView.backgroundColor = [UIColor whiteColor];
    _alertView.layer.cornerRadius = 10;
    
    UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectMake((CGRectGetWidth(_alertView.frame)-100*W)/2, 10*H, 100*W, 30*H)];
    alertLabel.text = @"选择地区";
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.font = [UIFont systemFontOfSize:18];
    alertLabel.textColor = [UIColor grayColor];
    [_alertView addSubview:alertLabel];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(0, CGRectGetHeight(_alertView.frame)-35*H+1, (CGRectGetWidth(_alertView.frame)-1)/2, 35*H-1);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [cancelBtn setTitleColor:[UIColor colorWithRed:(CGFloat)45/255 green:(CGFloat)143/255 blue:(CGFloat)247/255 alpha:1.0] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_alertView addSubview:cancelBtn];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake((CGRectGetWidth(_alertView.frame)+1)/2, CGRectGetHeight(_alertView.frame)-35*H+1, (CGRectGetWidth(_alertView.frame)-1)/2, 35*H-1);
    [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [confirmBtn setTitleColor:[UIColor colorWithRed:(CGFloat)45/255 green:(CGFloat)143/255 blue:(CGFloat)247/255 alpha:1.0] forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.tag = index;
    [_alertView addSubview:confirmBtn];
    
    UILabel *horiLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_alertView.frame)-35*H, CGRectGetWidth(_alertView.frame), 1)];
    horiLabel.backgroundColor = [UIColor grayColor];
    [_alertView addSubview:horiLabel];
    
    UILabel *verLabel = [[UILabel alloc] initWithFrame:CGRectMake((CGRectGetWidth(_alertView.frame)-1)/2, CGRectGetHeight(_alertView.frame)-35*H, 1, 35*H)];
    verLabel.backgroundColor = [UIColor grayColor];
    [_alertView addSubview:verLabel];
    
    UIPickerView *pickerView = [UIPickerView new];
    CALayer *viewLayer = pickerView.layer;
    [viewLayer setFrame:CGRectMake(30*W, 40*H, CGRectGetWidth(_alertView.frame)-60*W, CGRectGetHeight(_alertView.frame)-90*H)];
    [_alertView addSubview:pickerView];
    [_maskView addSubview:_alertView];
    [self.view addSubview:_maskView];
    return pickerView;
}

#pragma mark - 网络请求
//获取最新点赞信息
- (void)getNewestUpvoteRequest
{
    start=YES;
    end=YES;
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    
    NSDictionary *paramdic=@{@"loginId":[[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"]};
    NSString *url = [urlstring stringByAppendingString:@"getNewestUpvote.do"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSDictionary *dic = [NSDictionary new];
        if ([responseObject isKindOfClass:[NSData class]]) {
            dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }
        else if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            dic = responseObject;
        }
        
        NSLog(@"NewestUpvote-dic = %@", dic);
        
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        if (flag == 0) {
            _newestDict = dic;
            [self getMyUpvoteRequest];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
        NSLog(@"error = %@", error);
    }];
}

//获取我的点赞信息
- (void)getMyUpvoteRequest
{
    start=YES;
    end=YES;
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    
    NSDictionary *paramdic=@{@"loginId":[[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"]};
    NSString *url = [urlstring stringByAppendingString:@"getMyUpvotes.do"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSDictionary *dic = [NSDictionary new];
        if ([responseObject isKindOfClass:[NSData class]]) {
            dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }
        else if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            dic = responseObject;
        }
        
        NSLog(@"MyUpvote-dic = %@", dic);
        
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        if (flag == 0) {
            _commentsArray = [dic objectForKey:@"commentsLog"];
            [self reloadView];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
        NSLog(@"error = %@", error);
    }];
}

//查询用户信息（获取用户所属区域）
- (void)getUserInfoRequest
{
    start=YES;
    end=YES;
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    
    NSDictionary *paramdic=@{@"loginId":[[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"]};
    NSString *url = [urlstring stringByAppendingString:@"getUserInfo.do"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSDictionary *dic = [NSDictionary new];
        if ([responseObject isKindOfClass:[NSData class]]) {
            dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }
        else if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            dic = (NSDictionary *)responseObject;
        }
        
        NSLog(@"UserInfo-dic = %@", dic);
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        if (flag == 0) {
            _userListDic = dic;
            [self getNewestUpvoteRequest];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
        NSLog(@"error = %@", error);
    }];
}

//发送点赞请求
- (void)postUpvoteRequest
{
    start=YES;
    end=YES;
    PopLoadMsg *loadmsg=[PopLoadMsg new];
    
    NSDictionary *paramdic=@{@"loginId":[[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"],
                             @"province":[_userListDic objectForKey:@"province"],
                             @"city":[_userListDic objectForKey:@"city"],
                             @"district":_districtBtn.currentTitle,
                             @"psbName":[NSString stringWithFormat:@"%@派出所",_policeBtn.currentTitle],
                             @"comment":_inputField.text};
    NSString *url = [urlstring stringByAppendingString:@"postUpvote.do"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        NSDictionary *dic = [NSDictionary new];
        if ([responseObject isKindOfClass:[NSData class]]) {
            dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        }
        else if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            dic = (NSDictionary *)responseObject;
        }
        
        NSLog(@"dic = %@", dic);
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (msg) {
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        if (flag == 0) {
            NSLog(@"Upvote Success!");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"感谢您的赞赏" message:[NSString stringWithFormat:@"您的鼓励是我们前进的动力!"] delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
            [alert show];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
        NSLog(@"error = %@", error);
    }];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [_districtBtn setTitle:@"请选择区" forState:UIControlStateNormal];
    [_policeBtn setTitle:@"请选择" forState:UIControlStateNormal];
    _inputField.text = @"";
    [self getNewestUpvoteRequest];
}

#pragma mark - 点击事件
//收起键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_inputField resignFirstResponder];
}

- (void)selectDistrict
{
    NSString *proName = [_userListDic objectForKey:@"province"];
    NSString *cityName = [_userListDic objectForKey:@"city"];
    if (proName.length > 0 && cityName.length > 0) {
        _distArray = [_searchArea returnDistrictsWithProvince:proName City:cityName];
        _distPicker = [self showAlertWithIndex:100];
        _distPicker.delegate = self;
        _distPicker.dataSource = self;
        for (NSInteger i=0; i<_distArray.count; i++) {
            if ([_distArray[i] isEqualToString:_districtBtn.currentTitle]) {
                [_distPicker selectRow:i inComponent:0 animated:NO];
                break;
            }
            else {
                [_distPicker selectRow:_distArray.count/2 inComponent:0 animated:NO];
            }
        }
    }
    else {
        [PopMsg showMessage:@"数据下载失败，请检查网络" Lasttime:1.0f];
    }
}

- (void)selectPolicestation
{
    if ([_districtBtn.currentTitle isEqualToString:@"请选择区"]) {
        [PopMsg showMessage:@"请先选择区!" Lasttime:1.0f];
    }
    else {
        NSString *proName = [_userListDic objectForKey:@"province"];
        NSString *cityName = [_userListDic objectForKey:@"city"];
        NSString *distName = _districtBtn.currentTitle;
        _lpsArray = [_searchArea returnAddressWithProvince:proName City:cityName District:distName];
        if (_lpsArray.count == 0) {
            [PopMsg showMessage:@"当前地区没有派出所,请选择其他区域" Lasttime:1.0f];
        }
        else {
            _lpsPicker = [self showAlertWithIndex:101];
            _lpsPicker.delegate = self;
            _lpsPicker.dataSource = self;
            for (NSInteger i=0; i<_lpsArray.count; i++) {
                if ([_lpsArray[i] isEqualToString:_policeBtn.currentTitle]) {
                    [_lpsPicker selectRow:i inComponent:0 animated:NO];
                    break;
                }
                else {
                    [_lpsPicker selectRow:_lpsArray.count/2 inComponent:0 animated:NO];
                }
            }
        }
    }
}

//alertView的取消按钮点击事件
- (void)cancelBtnClicked:(UIButton *)btn
{
    [_alertView removeFromSuperview];
    _alertView = nil;
    [_maskView removeFromSuperview];
    _maskView = nil;
}

//alertView的确定按钮点击事件
- (void)confirmBtnClicked:(UIButton *)btn
{
    if (btn.tag == 100) {
        NSInteger num = [_distPicker selectedRowInComponent:0];
        NSString *district = _distArray[num];
        [_districtBtn setTitle:district forState:UIControlStateNormal];
        [_policeBtn setTitle:@"请选择" forState:UIControlStateNormal];
    }
    else if (btn.tag == 101) {
        NSInteger num = [_lpsPicker selectedRowInComponent:0];
        NSString *lpsString = _lpsArray[num];
        [_policeBtn setTitle:lpsString forState:UIControlStateNormal];
    }
    [_alertView removeFromSuperview];
    _alertView = nil;
    [_maskView removeFromSuperview];
    _maskView = nil;
}

- (void)upvote
{
    if (![_policeBtn.currentTitle isEqualToString:@"请选择"]) {
        [self postUpvoteRequest];
    }
    else {
        [PopMsg showMessage:@"请选择您要评价的派出所！" Lasttime:1.0f];
    }
}

#pragma mark- UIPickerView代理函数
//行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == _distPicker) {
        return _distArray.count;
    }
    else {
        return _lpsArray.count;
    }
}

//一共多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 30;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *pickerLabel = (UILabel *)view;
    if (pickerView == _distPicker) {
        if (!pickerLabel) {
            pickerLabel = [UILabel new];
            pickerLabel.text = _distArray[row];
            pickerLabel.textAlignment = NSTextAlignmentCenter;
            pickerLabel.textColor = [UIColor blackColor];
        }
    }
    else if (pickerView == _lpsPicker) {
        if (!pickerLabel) {
            pickerLabel = [UILabel new];
            pickerLabel.text = _lpsArray[row];
            pickerLabel.textAlignment = NSTextAlignmentCenter;
            pickerLabel.textColor = [UIColor blackColor];
        }
    }
    return pickerLabel;
}

#pragma mark- UITextView代理
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if (textView == _evalueContentField) {
        return NO;
    }
    return YES;
}

#pragma mark - button clicled handler -

- (void)goBackButtonClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
